# _*_ encoding: utf-8 _*_
# __author__ = 'lx'
"""
关于YoutubeAPI权限的开通
https://console.cloud.google.com/home/dashboard?project=ytbspd
对于只获取数据的接口，一般只需要apikey就行了，对于修改数据，创建数据类的接口需要申请Oauth

别人的例子
https://www.it610.com/article/1400963597126914048.htm
报错：
EOF occurred in violation of protocol (_ssl.c:1125)见
https://pythonmana.com/2021/03/20210315220037740p.html
https://github.com/psf/requests/issues/5740
"""
# from django.conf import settings

from common.request_base import RequestBase


class YoutubeAPI(RequestBase):
    """
    接口
    https://developers.google.com/youtube/v3/guides/implementation
    第一版暂时先用https接口，功能已经可以满足，如有需要，之后改成googleapi包:
    https://developers.google.com/youtube/v3/quickstart/python
    """
    APIs = {
        'videos': 'https://www.googleapis.com/youtube/v3/videos',
        'search': 'https://www.googleapis.com/youtube/v3/search',
        'channels': 'https://www.googleapis.com/youtube/v3/channels',
        'playlists': 'https://www.googleapis.com/youtube/v3/playlists',
        'playlistItems':
            'https://www.googleapis.com/youtube/v3/playlistItems',
        'commentThreads': 'https://www.googleapis.com/youtube/v3/commentThreads'
    }
    parts = ['id', 'snippet']

    def __init__(self, api_key):
        self.set_api_key(api_key)

    def get_video_info(self, video_id):
        api_url = self.get_api('videos')
        # part = "id, snippet, contentDetails, player, statistics, status, localizations"
        part = "id, snippet, statistics, status, localizations"

        params = {
            'id': video_id,
            'part': part
        }

        video = self.api_request(api_url, params)
        return video

    # 通用搜索
    # param     keyword     关键词
    # param     max_results 结果数量 可接受值为1到100
    # param     pageToken   下一页标识
    def general_search(self, keyword, max_results=10, page_token=None):
        api_url = self.get_api('search')
        params = {
            'q': keyword,
            'part': 'id, snippet',
            'maxResults': max_results
        }

        if page_token:
            params['pageToken'] = page_token

        objects = self.api_request(api_url, params)
        return objects

    def video_search(self, keyword, max_results=10, order=None, page_token=None, parts=None):
        api_url = self.get_api('search')
        if parts is not None:
            invalid_parts = [x for x in parts.split(',') if not x.strip() in self.parts]
            if len(invalid_parts) > 0:
                raise ValueError('Invalid Part Used: ' + ','.join(invalid_parts))
        else:
            parts = 'id, snippet'
        params = {
            'q': keyword,
            'type': 'video',
            'part': parts,
            'maxResults': max_results
        }
        if order:
            params['order'] = order

        if page_token:
            params['pageToken'] = page_token

        videos = self.api_request(api_url, params)
        return videos

    def video_search_in_channel(self, keyword="", channel_id=None, max_results=10,  page_token=None, **kwargs):
        api_url = self.get_api('search')
        params = {
            'q': keyword,
            'type': 'video',
            'channelId': channel_id,
            'part': 'id, snippet',
            'maxResults': max_results,
            'order': 'date',
            # 'relevanceLanguage': 'zh-Hans'
            # 'eventType': 'completed'    # 已首播的广播
        }

        if kwargs.get("order"):
            params['order'] = kwargs.get("order")
        if kwargs.get("eventType"):
            params['eventType'] = kwargs.get("eventType")
        if page_token:
            params['pageToken'] = page_token

        videos = self.api_request(api_url, params)
        return videos

    def get_channel_by_name(self, channel_name):
        api_url = self.get_api('channels')
        params = {
            'forUsername': channel_name,
            'part': 'id,snippet,contentDetails,statistics'
        }

        channel = self.api_request(api_url, params)
        return channel

    def get_channel_by_id(self, channel_id):
        api_url = self.get_api('channels')
        params = {
            'id': channel_id,
            'part': 'id,snippet,contentDetails,statistics'
        }

        channel = self.api_request(api_url, params)
        return channel

    def get_playlist_by_id(self, playlist_id):
        api_url = self.get_api('playlists')
        params = {
            'id': playlist_id,
            'part': 'id, snippet, status'
        }

        playlist = self.api_request(api_url, params)
        return playlist

    def get_playlist_by_channel_id(self, channel_id):
        api_url = self.get_api('playlists')
        params = {
            'channelId': channel_id,
            'part': 'id, snippet, status'
        }

        playlist = self.api_request(api_url, params)
        return playlist

    # 通过播放列表id获取播放列表
    def get_playlist_items_by_playlist_id(self, playlist_id, max_results=50, page_token=None):
        api_url = self.get_api('playlistItems')
        params = {
            'playlistId': playlist_id,
            'part': 'id, snippet, contentDetails, status',
            'maxResults': max_results
        }

        if page_token:
            params['pageToken'] = page_token

        playlist_items = self.api_request(api_url, params)
        return playlist_items

    # 通过视频id获取评论线
    # param     video_id        视频id
    # param     part            设定返回包含的资源'id,replies,snippet'
    # param     max_results     设定返回结果数
    # param     order           设定排序'time' or 'relevance'
    # param     pageToken       下一页标识
    # param     searchTerms     按措辞搜索(模糊匹配)
    def get_comment_threads_by_video_id(self, video_id, part='replies,snippet', max_results=20, order='time',
                                        page_token=None, searchTerms=None):
        api_url = self.get_api('commentThreads')
        params = {
            'videoId': video_id,
            'part': part,
            'maxResults': max_results,
            'order': order,
        }

        if page_token:
            params['pageToken'] = page_token
        if searchTerms:
            params['searchTerms'] = searchTerms

        comments = self.api_request(api_url, params)
        return comments

    async def get_comment_threads_by_video_id_async(self, video_id, part='replies,snippet', max_results=20, order='time',
                                        page_token=None, searchTerms=None):
        api_url = self.get_api('commentThreads')
        params = {
            'videoId': video_id,
            'part': part,
            'maxResults': max_results,
            'order': order,
        }

        if page_token:
            params['pageToken'] = page_token
        if searchTerms:
            params['searchTerms'] = searchTerms

        comments = await self.async_request(api_url, params)
        return comments


if __name__ == '__main__':
    api = YoutubeAPI('AIzaSyCH8phJq2VbKMCflkOyDE_4-vuR00EmPVw')
    # video = api.get_video_info('lRtedsK_6fs')
    # results = api.general_search('李子柒', max_results=10)
    # videos = api.video_search('我们中国人的开门七件事', max_results=10, order=None)
    # print(videos)
    # videos2 = api.video_search_in_channel(channel_id='UCCzN9KqigEvQZDXoRSXvjnQ', max_results=10,order="date")
    # print(videos2)
    #
    # channel = api.get_channel_by_name('Nathan Rich')
    channel2 = api.get_channel_by_id('UCCzN9KqigEvQZDXoRSXvjnQ')
    print(channel2)
    #
    # playlist = api.get_playlist_by_id('PLo4_KHAgJYFy8aLGOIpmmM8410Kz2kZlg')
    # playlist2 = api.get_playlist_by_channel_id('UCaSlyjhR4WC7QhYuaivxb6g')
    #
    # playlistItems = api.get_playlist_items_by_playlist_id('PLo4_KHAgJYFy8aLGOIpmmM8410Kz2kZlg', max_results=20)
    # comments = api.get_comment_threads_by_video_id('OSX3ik9Z4X8')

    # print(comments)
